package com.adam.masterSpringMVC4.controller.api;

import com.adam.masterSpringMVC4.weibo.WeiboUser;
import com.adam.masterSpringMVC4.weibo.WeiboUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api")
@Secured("ROLE_ADMIN")
public class WeiboUserApiController {

    private WeiboUserRepository userRepository;

    @Autowired
    public WeiboUserApiController(WeiboUserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @RequestMapping(value = "/users", method = RequestMethod.GET)
    public List<WeiboUser> findAll() {
        return userRepository.findAll();
    }

    @RequestMapping(value = "/users", method = RequestMethod.POST)
    public ResponseEntity<WeiboUser> createUser(@RequestBody WeiboUser user) {
        HttpStatus status = HttpStatus.OK;
        if(!userRepository.exists(user.getEmail())) {
            status = HttpStatus.CREATED;
        }
        WeiboUser saved = userRepository.save(user);
        return new ResponseEntity<>(saved, status);
    }

    @RequestMapping(value = "/user/{email}", method = RequestMethod.PUT)
    public ResponseEntity<WeiboUser> updateUser(@PathVariable String email, @RequestBody WeiboUser user) {
        if(!userRepository.exists(email)) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        WeiboUser saved = userRepository.save(email, user);
        return new ResponseEntity<>(saved, HttpStatus.OK);
    }

    @RequestMapping(value = "/user/{email}", method = RequestMethod.DELETE)
    public ResponseEntity<WeiboUser> deleteUser(@PathVariable String email) {
        if(!userRepository.exists(email)) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        userRepository.delete(email);
        return new ResponseEntity<>(HttpStatus.OK);
    }

}
